package com.camera2.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.media.Image;
import android.media.ImageReader;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.camera2.Utils.ByteBitmap;
import com.camera2.http.SendImage;
import com.camera2.local.SaveImage;

import java.nio.ByteBuffer;
import java.util.Arrays;


public class TakePicture extends AppCompatActivity implements View.OnClickListener {

    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();

    static {
        ORIENTATIONS.put(Surface.ROTATION_0, 90);
        ORIENTATIONS.put(Surface.ROTATION_90, 0);
        ORIENTATIONS.put(Surface.ROTATION_180, 270);
        ORIENTATIONS.put(Surface.ROTATION_270, 180);
    }

    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private ImageView iv_show;
    private CameraManager mCameraManager;
    private Handler childHandler, mainHandler;
    private String mCameraID;
    private ImageReader mImageReader;
    private CameraCaptureSession mCameraCaptureSession;
    private CameraDevice mCameraDevice;


    private LinearLayout ll_imgtake;
    private LinearLayout ll_imgshow;

    private EditText et_1;
    private EditText et_2;
    private EditText et_3;

    private String stret_1;
    private String stret_2;
    private String stret_3;

    private CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            mCameraDevice = cameraDevice;
            takePreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            if (null != mCameraDevice) {
                mCameraDevice.close();
                TakePicture.this.mCameraDevice = null;
            }
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int i) {
            Toast.makeText(TakePicture.this, "摄像头开启失败", Toast.LENGTH_SHORT).show();
        }
    };

    private void takePreview() {
        try {
            final CaptureRequest.Builder previewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            previewRequestBuilder.addTarget(mSurfaceHolder.getSurface());
            mCameraDevice.createCaptureSession(Arrays.asList(mSurfaceHolder.getSurface(), mImageReader.getSurface()), new CameraCaptureSession.StateCallback() // ③
            {
                @Override
                public void onConfigured(CameraCaptureSession cameraCaptureSession) {
                    if (null == mCameraDevice) return;
                    mCameraCaptureSession = cameraCaptureSession;
                    try {
                        previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                        previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                        CaptureRequest previewRequest = previewRequestBuilder.build();
                        mCameraCaptureSession.setRepeatingRequest(previewRequest, null, childHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(TakePicture.this, "配置失败", Toast.LENGTH_SHORT).show();
                }
            }, childHandler);


        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take);
        initView();
    }

    private void initView() {
        findViewById(R.id.bt_album).setOnClickListener(this);
        findViewById(R.id.bt_takepicture).setOnClickListener(this);
        findViewById(R.id.bt_trans).setOnClickListener(this);
        findViewById(R.id.bt_submit).setOnClickListener(this);

        ll_imgshow = findViewById(R.id.ll_imgshow);
        ll_imgtake = findViewById(R.id.ll_imgtake);
        ll_imgshow.setVisibility(View.GONE);
        ll_imgtake.setVisibility(View.VISIBLE);

        et_1 = findViewById(R.id.et_1);
        et_2 = findViewById(R.id.et_2);
        et_3 = findViewById(R.id.et_3);

        iv_show = findViewById(R.id.iv_show_camera2_activity);
        mSurfaceView = findViewById(R.id.surface_view_camera2_activity);

        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setKeepScreenOn(true);
        mSurfaceHolder.setKeepScreenOn(true);
        mCameraID = "" + CameraCharacteristics.LENS_FACING_FRONT;//hou
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                initCamera2();
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                if (null != mCameraDevice) {
                    mCameraDevice.close();
                    TakePicture.this.mCameraDevice = null;
                }
            }
        });
    }

    private void initCamera2() {
        HandlerThread handlerThread = new HandlerThread("Camera2");
        handlerThread.start();
        childHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());
//        mCameraID = "" + CameraCharacteristics.LENS_FACING_FRONT;//hou
        mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG, 50);
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader imageReader) {

                Image image = imageReader.acquireNextImage();
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];

                buffer.get(bytes);
                final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                ByteBitmap bb=new ByteBitmap();
                byte[] byt=bb.Bitmap2Bytes(bitmap);
                SaveImage.saveImg(getApplicationContext(),byt);
                if (bitmap != null) {
                    ll_imgshow.setVisibility(View.VISIBLE);
                    ll_imgtake.setVisibility(View.GONE);
                    iv_show.setImageBitmap(bitmap);
                }

                takePreview();

            }
        }, mainHandler);
        mCameraManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        try {
            mCameraManager.openCamera(mCameraID, stateCallback, mainHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_takepicture:
                takePicture();
                break;
            case R.id.bt_album:
                openAlbum();
                break;

            case R.id.bt_trans:
                mCameraDevice.close();
                TakePicture.this.mCameraDevice = null;
                if (mCameraID.equals("0"))
                    mCameraID = "" + CameraCharacteristics.LENS_FACING_BACK;//hou
                else mCameraID = "" + CameraCharacteristics.LENS_FACING_FRONT;//hou
                initCamera2();
                break;
            case R.id.bt_submit:

                submit();
                break;
        }
    }

    public void submit() {
        stret_1 = et_1.getText().toString().trim();
        stret_2 = et_2.getText().toString().trim();
        stret_3 = et_3.getText().toString().trim();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String log = SendImage.send(getApplicationContext(), stret_1, stret_2, stret_3);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = log;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 0;
                    handler.sendMessage(msg);
                }

            }
        }).start();

    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String info = (String) msg.obj;
                    if (info.equals("success")) {
                        Toast.makeText(getApplicationContext(), "数据已提交", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getApplicationContext(), Frament.class);
                        startActivity(intent);
                        finish();
                    }
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "连接网络失败,请检查网络是否连接", Toast.LENGTH_SHORT)
                            .show();
                    break;
            }
        }
    };

    //打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    } //选择好图片之后在这里验证系统版本

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case 2:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }


    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    //如果是4.4以下版本直接传入
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    //获取图片真实路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //获取内容解析器查询
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //显示图片
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            //图片的文件路径
//            showProgressDialog("请稍候!", "正在上传照片...");
//            String imgpath = upload.uploadImage(imagePath, empId);

//            if (!imgpath.equals("")) {

//                progressDialog.dismiss();
            SendImage.imagePath=imagePath;
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ll_imgshow.setVisibility(View.VISIBLE);
            ll_imgtake.setVisibility(View.GONE);
            iv_show.setImageBitmap(bitmap);
//            Toast.makeText(this, "上传照片成功", Toast.LENGTH_SHORT).show();
//            } else Toast.makeText(this, "上传照片失败，请重新上传", Toast.LENGTH_SHORT).show();


        } else {
            Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void takePicture() {
        if (mCameraDevice == null) return;
        final CaptureRequest.Builder captureRequestBuilder;
        try {
            captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureRequestBuilder.addTarget(mImageReader.getSurface());
            captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
            CaptureRequest mCaptureRequest = captureRequestBuilder.build();
            mCameraCaptureSession.capture(mCaptureRequest, null, childHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Toast.makeText(getApplicationContext(), "KEYCODE_BACK被按下", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, Frament.class);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
